import time
from bcat.app.application import ClientApplication, IApplication
from bcat.process.executables import Python

from bcat.rpc.client.server_proxies.common_server_proxy import CommonServerProxy
from bcat.rpc.client.server_proxy_impls.jsonrpclib_server_proxy_impl import JsonRpcLibServerProxyImpl
class MainClientApplication(ClientApplication):
    def __init__(self): 
        pass

    def init(self) -> bool:
        script_path = "/home/chenglun/dev/bcat/src/backend/local/demo/common_server_app_demo.py"
        url = "http://127.0.0.1:5000/api"
        try:
            print("start process")
            self.__process = Python.default().execute(script_path)
            print(f"{self.__process}")
            self.__server_proxy = CommonServerProxy(url, JsonRpcLibServerProxyImpl(url))
        except Exception as e:
            print(f"init failed: {e}")
            return False
        return True



    def deinit(self) -> bool:
        print("enter clear resource")
        self.__server_proxy = None
        self.__process.terminate().wait(4)
        self.__process = None
        return True

    def _wait(self, secs) -> None:
        print(f"wait {secs} seconds")
        time.sleep(secs)

    def run(self) -> IApplication:
        print("demo client start running")
        if not self.init() :
            print("init failed")
            return self

        try:
            print("waiting subprocess to be started")
            self._wait(2)

            while True:
                print("call tick: ", self.__server_proxy.tick())
                print("call exit: ", self.__server_proxy.exit())
                self._wait(1)

        except Exception as e:
            print(f"got error when running: {e}")

        finally:
            self.deinit()

        return self

MainClientApplication().run()
